﻿using ProjectCloth.Entity;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class InStockItemListFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        public InStockItemListFrm()
        {
            InitializeComponent();
            companyCbb.DataSource = db.Companies.ToList();
            companyCbb.ValueMember = "Id";
            companyCbb.DisplayMember = "Name";
            companyCbb.SelectedValue = 0;
            outmoneycbb.DataSource = db.CashAccounts.ToList();
            outmoneycbb.DisplayMember = "TradeTypeName";
            outmoneycbb.ValueMember = "Id";
            outmoneycbb.SelectedValue = 0;
            var selectList = new List<DataItemStatus>();
            selectList.Add(new DataItemStatus()
            {
                Id = 0,
                Name = "未支付"
            });
            selectList.Add(new DataItemStatus()
            {
                Id = 1,
                Name = "已支付"
            });
            //selectList.Add(new DataItemStatus()
            //{
            //    Id = 2,
            //    Name = "作废"
            //});
            statusCombobox.DataSource = selectList;
            statusCombobox.DisplayMember = "Name";
            statusCombobox.ValueMember = "Id";
            statusCombobox.SelectedValue = -1;

        }
        private List<InstockItemModel> Sql
        {
            get
            {
                var startTime = startDatePiker.Value.Date;
                var endTime = endDatePicker.Value.AddDays(1).Date;
                var instockNo = InstockNoTxt.Text != null ? InstockNoTxt.Text : "";
                var isPay = statusCombobox.SelectedValue != null ? ((int)statusCombobox.SelectedValue == 0 ? false : true) : false;
                var selCompanyId = companyCbb.SelectedValue != null ? (int)companyCbb.SelectedValue : 0;
                var itemList = (from o in db.InStockItems.AsNoTracking()
                                    //.Where(o => o.MakeTime > startTime && o.MakeTime < endTime
                                    //&& (string.IsNullOrEmpty(instockNo) || o.InstockItemNo == instockNo)
                                    //&& (statusCombobox.SelectedValue == null || isPay == o.IsPaid)
                                    //&& (string.IsNullOrEmpty(InstockproductTxt.Text) || o.InstockProductName.Contains(InstockproductTxt.Text.ToUpper()))
                                    //&& (companyCbb.SelectedValue == null || selCompanyId == o.CompanyId))
                                join oi in db.SaleOrderItems on o.SaleOrderItemId equals oi.Id
                                join pr in db.Products on oi.ProductId equals pr.Id
                                where ((string.IsNullOrEmpty(orderproductnoTxt.Text) || pr.ProductNo.Contains(orderproductnoTxt.Text.ToUpper()))
                                && (string.IsNullOrEmpty(orderNoTxt.Text) || oi.OrderNo.Contains(orderNoTxt.Text.ToUpper())))
                                && (o.MakeTime > startTime && o.MakeTime < endTime)
                                && (string.IsNullOrEmpty(instockNo) || o.InstockItemNo == instockNo)
                                && (statusCombobox.SelectedValue == null || isPay == o.IsPaid)
                                && (string.IsNullOrEmpty(InstockproductTxt.Text) || o.InstockProductName.Contains(InstockproductTxt.Text.ToUpper()))
                                && (companyCbb.SelectedValue == null || selCompanyId == o.CompanyId)
                                select new InstockItemModel
                                {
                                    CompanyName = o.CompanyNo,
                                    InStockNo = o.InstockItemNo,
                                    InStockProductName = o.InstockProductName,
                                    Quantity = o.Quantity,
                                    Amount = o.Amount,
                                    Price = o.Price,
                                    SaleOrderNo = o.SaleOrderNo,
                                    saleProduct = pr.ProductNo,
                                    Remark = o.Remark,
                                    Time = o.MakeTime,
                                    Status = o.IsPaid ? "已付款" : "未付",
                                    Id = oi.Id
                                }).ToList();
                return itemList;
            }
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = Sql;
        }

        private void exportBtn_Click(object sender, EventArgs e) => Helper.ExportDgv(dataGridView1, "进货信息查询");//MessageBox.Show("暂时无法导出");
        /// <summary>
        /// 批量付款
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void batchPayBtn_Click(object sender, EventArgs e)
        {
            try
            {
                var listId = new List<int>();
                var accountId = 0;
                var account = new CashAccount();
                if (outmoneycbb.SelectedValue != null)
                {
                    accountId = (int)outmoneycbb.SelectedValue;
                    account = db.CashAccounts.Find(accountId);
                }
                else
                {
                    MessageBox.Show("请选择付款账号！");
                    return;
                }
                if (companyCbb.SelectedValue == null)
                {
                    MessageBox.Show("请选择相同供应商！");
                    return;
                }
                decimal varialAmount = 0;
                decimal preAmount = account.Amount;
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    if (dataGridView1.Rows[i] != null & dataGridView1.Rows[i].Cells["checkboxSel"] != null && (bool)dataGridView1.Rows[i].Cells["checkboxSel"].EditedFormattedValue == true)
                    {
                        var id = dataGridView1.Rows[i].Cells["Id"].Value;
                        if (id != null)
                        {
                            listId.Add((int)id);
                        }
                    }
                }
                var count = 0;
                foreach (var p in listId)
                {
                    var item = db.InStockItems.FirstOrDefault(o => o.SaleOrderItemId == p);
                    if (item != null && !item.IsPaid)
                    {
                        item.IsPaid = true;
                        item.PayTime = DateTime.Now;
                        item.PayAccountId = accountId;
                        item.Remark = "批量付款";
                        varialAmount += item.SaleOrderNo.EndsWith("T") ? -item.Amount : item.Amount;//变更退货单进货形成的流水
                        count++;
                    }
                }
                account.Amount -= varialAmount;
                account.OriginalAmount = preAmount;
                account.UpdateTime = DateTime.Now;
                var log = new CashAccountLog()
                {
                    OriginalAmount = preAmount,
                    VariableAmount = -varialAmount,
                    MakerTime = DateTime.Now,
                    MakerId = LoginInfo.GetLoginInfo().UserId,
                    CashAccountId = accountId,
                    CreateTime = DateTime.Now,
                    CurrentAmount = account.Amount,
                    Source = "批量付款",
                    RelatedObject = companyCbb.Text,
                    Remark = "批量付款" + count.ToString() + "进货单",
                    LoginId = LoginInfo.GetLoginInfo().UserId,
                };
                db.CashAccountLogs.Add(log);
                var result = db.SaveChanges();
                if (result > 0)
                {
                    MessageBox.Show("批量修改了" + count + "单");
                }

            }
            catch (Exception)
            {
                MessageBox.Show("出现错误！");
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "SaleOrderNo")
                {
                    var main = MainFrm.CreateInstrance();
                    var tab = main.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
                    var tabControl = tab;
                    if (tab != null)
                    {
                        tabControl = (TabControl)tab as TabControl;
                    }
                    if (dataGridView1.Rows[e.RowIndex].Cells["SaleOrderNo"].Value == null) return;
                    var orderNo = dataGridView1.Rows[e.RowIndex].Cells["SaleOrderNo"].Value.ToString();
                    new AddTab(new SaleOrderFrm(orderNo), "SaleOrderFrmSearch", "销售单查询", tabControl);
                    //new SaleOrderFrm(orderNo).ShowDialog();
                }
                else if (dataGridView1.Columns[e.ColumnIndex].Name != "saleProduct")
                {
                    #region 修改进货
                    var itemId = dataGridView1.CurrentRow.Cells["Id"].Value;
                    if (itemId != null && (int)itemId > 0)
                    {
                        var main = MainFrm.CreateInstrance();
                        var tab = main.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
                        var tabControl = tab;
                        if (tab != null)
                        {
                            tabControl = tab as TabControl;
                        }
                        dataGridView1.CurrentRow.Selected = true;
                        var instockfrm = new InStockItemFrm((int)itemId);
                        instockfrm.StartPosition = FormStartPosition.Manual;
                        instockfrm.Location = new Point(this.Right + 400 - instockfrm.Width, this.Bottom - instockfrm.Height);
                        instockfrm.ShowDialog();//或f.Show(this);或f.Show()

                    }
                    #endregion
                }

            }
        }
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var sql = Sql;// GetList();
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column != null)
            {
                if (column.Name == "CompanyName")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.CompanyName).ToList();
                }
                else if (column.Name == "SaleOrderNo")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.SaleOrderNo).ToList();
                }
                else if (column.Name == "saleProduct")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.saleProduct).ToList();
                }
                else if (column.Name == "Amount")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Amount).ToList();
                }
                else if (column.Name == "Time")
                {
                    dataGridView1.DataSource = sql.OrderByDescending(o => o.Time).ToList();
                }
            }
        }
        private void dataGridView1_ColumnHeaderDoubleMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var sql = Sql;// GetList();
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column != null)
            {
                if (column.Name == "CompanyName")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.CompanyName).ToList();
                }
                else if (column.Name == "SaleOrderNo")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.SaleOrderNo).ToList();
                }
                else if (column.Name == "saleProduct")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.saleProduct).ToList();
                }
                else if (column.Name == "Amount")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Amount).ToList();
                }
                else if (column.Name == "Time")
                {
                    dataGridView1.DataSource = sql.OrderBy(o => o.Time).ToList();
                }
            }

        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGridView1.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }


    }
    public class InstockItemModel
    {
        public string CompanyName { get; set; }
        public string InStockNo { get; set; }
        public string InStockProductName { get; set; }
        public decimal Quantity { get; set; }
        public decimal Amount { get; set; }
        public decimal Price { get; set; }
        public string SaleOrderNo { get; set; }
        public string saleProduct { get; set; }
        public string Remark { get; set; }
        public DateTime? Time { get; set; }
        public string Status { get; set; }
        public int Id { get; set; }
    }
}
